home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7831 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  55 lines

  1. Path: anvil.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Generating pointer to struct from string
  5. Date: 27 Feb 1996 12:45:49 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4gvqhtINNi79@anvil.ugrad.cs.ubc.ca>
  8. References: <4grk4g$hep@fmsu03.fm.intel.com>
  9. NNTP-Posting-Host: anvil.ugrad.cs.ubc.ca
  10.  
  11. In article <4grk4g$hep@fmsu03.fm.intel.com>,
  12. Vishram Dalvi <vdalvi@mcd.intel.com> wrote:
  13. >Hello,
  14. >
  15. >Say I have 3 structs aaa, bbb and ccc of type foo:
  16. >
  17. >struct foo {
  18. >    int flag;
  19. >    char name[30]
  20. >} aaa, bbb, ccc;
  21. >
  22. >I assign some values to the data members of all 3 structs. Now I prompt the
  23. >user for the name of one of these structs. I read in the user entry into a
  24. >char array. Assume that the user entered "aaa". How can I generate a pointer
  25. >to the struct "aaa" from the user entry?
  26. >I do not want a switch/case table (if user entered "aaa", access members of
  27. >"aaa", if user entered "bbb"...).
  28. >How do I cast a string into a struct address??
  29. >Thanks in advance,
  30.  
  31. The names of C language objects are not accessible at run time. They are
  32. temporary symbols needed to achieve a translation into the execution language.
  33.  
  34. This sort of thing is possible from debuggers, which have access to a symbol
  35. table and other debugging information emitted by the compiler. In theory, you
  36. could (in a very operating-system specific way) have a program search its own
  37. debugging information (assuming it's available) and come up with a mapping for
  38. a symbol name to an address.
  39.  
  40. The easiest way to do it is to just declare an array of strings whose names
  41. match your structures, and search this array. You can sort it with qsort() and
  42. then use bsearch(), if it is large.
  43.  
  44. Better yet, make each name a field of the structure, and put the structures
  45. into an array:
  46.  
  47. struct foo {
  48.     char name[8];
  49.     int value;
  50. } arr[] = { { "aaa" }, { "bbb" }, { "ccc" }};
  51.  
  52.  
  53. -- 
  54.  
  55.